﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NGinnBPM.Runtime.Messages;
using NGinnBPM.Lib.Exceptions;
using NGinnBPM.Lib.Schema;
using NGinnBPM.MessageBus;
using NGinnBPM.Lib.Interfaces;
using System.Runtime.Serialization;
using NGinnBPM.Services;
 
namespace NGinnBPM.Runtime.Tasks
{
    /// <summary>
    /// Task instance for debugging purposes. Must be manually completed and logs all activity.
    /// </summary>
    [Serializable]
    [DataContract]
    public class NotificationTaskInstance : AtomicTaskInstance
    {
        public override void Enable(Dictionary<string, object> inputData)
        {
            base.Enable(inputData);
            DoSendMessage();
        }

      
        [DataMember]
        [TaskParameter(IsInput=true, Required=false)]
        public string SenderEndpoint { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string SenderName { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string TemplateName { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string Subject { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string To { get; set; }

        [DataMember]
        [TaskParameter(IsInput = true, Required = false)]
        public string BodyText { get; set; }


        private void DoSendMessage()
        {
            try
            {
                IEmailSender sender = Context.ServiceLocator.GetInstance<IEmailSender>(SenderName);
                SendEmailMessage sm = new SendEmailMessage();
                sm.TaskInstanceId = InstanceId;
                sm.TaskId = TaskId;
                sm.DefinitionId = ParentProcess.DefinitionId;
                sm.CorrelationId = InstanceId;
                sm.TemplateName = TemplateName;
                sm.EmailSender = SenderName;
                sm.BodyText = BodyText;
                sm.Subject = Subject;
                sm.Data = TaskData;
                if (To != null)
                    sm.Recipients = To.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                sender.Send(sm);
                Complete(null, null);
            }
            catch (NGinnException nex)
            {
                if (nex.Permanent)
                {
                    Fail(nex.Message);
                    return;
                }
                throw;
            }
        }
    }
}
